package classes.Commands
{
	import UIUtils.uif_util;
	
	import components.editor.c_baseEditor;
	import components.editor.c_baseElement;
	import components.editor.c_bitmapElement;
	
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.BlendMode;
	import flash.display.Shape;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class c_cropCommand extends c_baseBitmapCommand {
		private var _outside	: Boolean;
		private var _backMatrix	: Matrix;
		private var _newMatrix	: Matrix;
		private var _backBmd	: BitmapData;
		private var _newBmd		: BitmapData;
		public function c_cropCommand(a_editor:c_baseEditor, a_element: c_bitmapElement, a_outside: Boolean) {
			super(a_editor, a_element);
			_outside = a_outside;
		}
		
		private function drawShape(): void {
			
			var mat: Matrix = editor.dragRect.matrix.clone();
			var m2: Matrix = element.matrix.clone();
			m2.invert();
			mat.concat(m2);
			
			var shape: Shape = new Shape();
			shape.graphics.beginFill(0, 1);
			shape.graphics.drawRect(0, 0, editor.dragRect.width, editor.dragRect.height);
			shape.graphics.endFill();
			if (_outside) {
				var eraser: BitmapData = new BitmapData(bmd.width, bmd.height, true, 0xFF000000);
				eraser.draw(shape, mat, null, BlendMode.ERASE);
				bmd.draw(new Bitmap(eraser), null, null, BlendMode.ERASE);
				eraser.dispose();
				afterCropOutside();
			} else {
				_newBmd = bmd.clone();
				_newBmd.draw(shape, mat, null, BlendMode.ERASE);
				_newMatrix = element.matrix.clone();
			}
		}
		
		protected function afterCropOutside(): void {
			var rect: Rectangle = bmd.getColorBoundsRect(0xFF000000, 0, false);
			
			if (rect.size.length > 0) {
				var a_tmp: BitmapData = new BitmapData(rect.width, rect.height, true, 0);
				a_tmp.copyPixels(bmd, rect, uif_util.NULLPOINT);
				bmd.dispose();
				
				_newBmd = new BitmapData(rect.width, rect.height, true, 0);
				_newBmd.copyPixels(a_tmp, a_tmp.rect, uif_util.NULLPOINT);
				a_tmp.dispose();
				
				_newMatrix = new Matrix(1, 0, 0, 1, rect.x, rect.y);
				_newMatrix.concat(element.matrix);
			}
		}
		
		protected function setNewBmd(a_bmd: BitmapData, a_matrix: Matrix): void {
			bmd.dispose();
			bmd = a_bmd.clone();
			element.resize(a_bmd.width, a_bmd.height);
			element.matrix = a_matrix;
			editor.dragRect.updateFromLinkControl();
		}
		
		override public function Execute():void {
			super.Execute();
			if (!_newBmd) {
				_backMatrix = element.matrix.clone();
				_backBmd 	= bmd.clone();
				drawShape();
			}
			setNewBmd(_newBmd.clone(), _newMatrix);
			editor.dragRect.nodragMode = false;
		}
		
		override public function unExecute():void {
			super.unExecute();
			setNewBmd(_backBmd.clone(), _backMatrix);
		}
		
		override public function dispose():void {
			super.dispose();
			_backBmd.dispose();
			_newBmd.dispose();
		}
	}
}